module.exports = class extends think.Service {
  constructor (modelName) {
    super()
    this.resource = modelName
    this.modelInstance = yy.model(modelName)
  }
  async get ({where, order, page, pageSize, first, last, id}) {
    where = where || {}
    page = page || 1
    pageSize = pageSize || 20
    order = order || {}
    let d = {}
    if (id) {
      where._id = id
      d = await this.modelInstance.where(where).find()
    } else if (first || last) {
      d = await this.modelInstance.where(where).order(order).cursor(first, last, pageSize)
    } else {
      const list = await this.modelInstance.where(where).order(order).page(page, pageSize).select()
      const count = await this.modelInstance.where(where).count()
      d = {list, count, page, pageSize}
    }
    return d
  }
  async post (data) {
    const d = await this.modelInstance.add(data)
    return d
  }
  async del (where) {
    const rows = await this.modelInstance.where(where).remove()
    return { affectedRows: rows }
  }
  async put (where, data) {
    const rows = await this.modelInstance.where(where).update(data)
    return { affectedRows: rows }
  }
  async forbid (where) {
    const rows = await this.modelInstance.where(where).update({status: 1})
    return { affectedRows: rows }
  }
  async revert (where) {
    const rows = await this.modelInstance.where(where).update({status: 0})
    return { affectedRows: rows }
  }
}
